import React, { useReducer } from 'react';

const context1 = React.createContext();
const MyProvider = context1.Provider;

const Provider = props => {
  let initSate, reducers;
  let store = props.store;

  if (Array.isArray(store)) {
    for (let i = 0; i < store.length; i++) {
      initSate = { ...initSate, ...store[i].state };
      reducers = { ...reducers, ...store[i].reducers };
    }
  } else {
    // store不是数组
    initSate = store.state != null ? store.state : {};
    reducers = store.reducers;
  }

  const reducer = (state, action) => {
    let t = reducers[action.type];
    return t(state, action);
  };

  const [state, dispatch] = useReducer(reducer, initSate);

  const proxyDispatch = (action) => {
    let red = reducers[action.type];
    if (red != null) {
      console.log("dispatch...")
      dispatch(action);
    }
  };

  return (
    <MyProvider value={{ state, dispatch: proxyDispatch }}>
      {props.children}
    </MyProvider>
  );
}

export { context1, Provider };
